<template>
  <a-tabs v-model:activeKey="activeKey" tabPosition="left" class="h-full">
    <a-tab-pane 
      v-for="(item, index) in commissionList"
      :key="`commission-${index}-${index + 1}`"
      forceRender
    >
      <!-- 选择卡头插槽 -->
      <template #tab>
        <AuditOutlined />
        <a-tooltip
          :title="`${ item?.deptName || '中心'}委托`"
          placement="top"
        >
          <span class="tab-name">{{ `${item?.deptName || '中心'}委托` }}</span>
        </a-tooltip>
      </template>
      <workFlowDetail v-if="item.flowId" :config="flowConfig(item)" />
      <Form
        v-else
        :ref="setCommissionRefs"
        :commission="true"
        :contract-data="item"
        :master-contract-data="masterContractData"
      />
    </a-tab-pane>
    <a-tab-pane 
      v-for="(item, index) in subcontractList"
      :key="`subcontract-${index}-${commissionList.length + index + 1}`"
      forceRender
    >
      <template #tab>
        <ApartmentOutlined />
        <a-tooltip
          :title="`${item?.contractSigningPartyBName || '公司'}分包合同`"
          placement="top"
        >
          <span class="tab-name">{{ `${item?.contractSigningPartyBName || '公司'}分包合同` }}</span>
        </a-tooltip>
      </template>
      <workFlowDetail v-if="item.flowId" :config="flowConfig(item)" />
      <Form
        v-else
        :ref="setSubcontractRefs"
        :contract-data="item"
        :master-contract-data="masterContractData"
      />
    </a-tab-pane>
  </a-tabs>
  <ContractPush class="push-eare" :popup-title="'内部分包合同'" @register="registerContractPush"/>
</template>

<script name="confirmTask" setup>
  import { ref, inject, onBeforeUpdate } from 'vue';
  import { useMessage } from '@/hooks/web/useMessage';
  import { usePopup } from '@/components/Popup';
  import { AuditOutlined, ApartmentOutlined } from '@ant-design/icons-vue';
  import { getPackageTrustList, saveOrUpdatePackageContract } from '@/views/project/internalOperations/common/api';
  import { resdata } from '@/views/project/internalOperations/common/deliveryListConfig';
  import Form from './contractInfo.vue';
  import workFlowDetail from '@/views/workFlow/workFlowDetail/index.vue';
  import ContractPush from '@/views/project/contractRegistration/components/ContractPush.vue';

  const { createMessage } = useMessage();
  const [ registerContractPush, { openPopup: openContractPush } ] = usePopup();
  const projectInfo = inject('projectInfo');
  // 使用数组存储所有ContractInfo组件的ref
  const commissionRefs = ref([]);
  const subcontractRefs = ref([]);
  const activeKey = ref('commission-0-1');
  const canReturn = ref(false); // 上一步按钮权限（全部为待提交）
  // 委托数据
  const commissionList = ref([]);
  // 分包数据
  const subcontractList = ref([]);
  // 主合同信息
  const masterContractData = ref([]);

  const setCommissionRefs = (el) => {
    if (el && !commissionRefs.value.includes(el)) {
      commissionRefs.value.push(el);
    }
  };

  const setSubcontractRefs = (el) => {
    if (el && !subcontractRefs.value.includes(el)) {
      subcontractRefs.value.push(el);
    }
  };

  // 审批数据
  const flowConfig = (data) => {
    return {
      taskId: data.flowTaskId,
      flowId: data.flowId,
      opType: 6,
    };
  };

  // 获取上一步的权限 [全部为待提交0==true]
  const getCanReturn = (info) => {
    // 处理委托和分包数据可能为空情况（空数组视为满足条件）
    const commissionArray = info.contractTrustVoList || [];
    const subcontractArray = info.contractPackageVoList || [];

    // 检查委托数组
    const isCommissionAllZero = commissionArray.length > 0
      ? commissionArray.every(item => item.spStatus == 0)
      : true;
    
    // 检查分包数组
    const isSubcontractAllZero = subcontractArray.length > 0
      ? subcontractArray.every(item => item.spStatus == 0)
      : true;

    // 两个数组都满足条件时返回true
    return isCommissionAllZero && isSubcontractAllZero;
  };

  // 数据赋值函数
  const assignData = (info) => {
    // 委托合同、分包合同、主合同数据
    commissionList.value = info.contractTrustVoList || [];
    subcontractList.value = info.contractPackageVoList || [];
    masterContractData.value = info.salesProjectContractVo || {};

    // 初始化activeKey（优先委托）
    if (commissionList.value.length > 0) {
      activeKey.value = `commission-0-1`; // 第一个委托标签
    } else if (subcontractList.value.length > 0) {
      activeKey.value = `subcontract-0-1`; // 第一个分包标签
    }
  };

  const initTasks = async (data = null) => {
    const { contractCode } = projectInfo.value;
    // 前端假数据 resdata ||
    let info = data || (await getPackageTrustList(contractCode))?.data;
    if(info) {
      assignData(info);
      canReturn.value = getCanReturn(info);
    }
  };

  // 校验所有tab的填写情况
  const validateAllForms = async () => {
    let allValid = true;

    // 校验委托表单
    for (let i = 0; i < commissionRefs.value.length; i++) {
      const form = commissionRefs.value[i];
      if (!form) continue;
      try {
        await form.validateFields();
      } catch (error) {
        allValid = false;
        activeKey.value = `commission-${i}-${i + 1}`;
        const tabName = commissionList.value[i]?.deptName || '中心';
        createMessage.warning(`${tabName}委托表单校验失败，请检查！`);
        break;
      }
    }

    if (!allValid) return false;

    // 校验分包表单
    for (let i = 0; i < subcontractRefs.value.length; i++) {
      const form = subcontractRefs.value[i];
      if (!form) continue;
      try {
        await form.validateFields();
      } catch (error) {
        allValid = false;
        activeKey.value = `subcontract-${i}-${commissionList.value.length + i + 1}`;
        const tabName = subcontractList.value[i]?.contractSigningPartyBName || '公司';
        createMessage.warning(`${tabName}分包表单校验失败，请检查！`);
        break;
      }
    }
    return allValid;
  };

  const saveAll = async () => {
    try {
      const allValid = await validateAllForms();
      if (!allValid) return;
      // 收集数据
      const formData = {
        contractTrustVoList: [],
        contractPackageVoList: [],
        contractCode: unref(projectInfo).contractCode,
        state: '1',
      };

      // 收集委托表单数据
      if (commissionRefs.value.length > 0) {
        for (const form of commissionRefs.value) {
          const data = await form.getFieldsValue();
          let where = {
            ...data,
            contractTrustPaymentInfos: data.contractPaymentTerms,
          };
          formData.contractTrustVoList.push(where);
        }
      }

      // 收集分包表单数据
      if (subcontractRefs.value.length > 0) {
        for (const form of subcontractRefs.value) {
          const data = await form.getFieldsValue();
          let where = {
            ...data,
            contractPaymentInfosPackage: data.contractPaymentTerms,
          };
          formData.contractPackageVoList.push(where);
        }
      }

      // console.log("4.1-提交参数", formData);
      const res = await saveOrUpdatePackageContract(formData);
      // console.log("4.2-提交数据-res", res);
      if(res.code==200) createMessage.success('提交成功！');
      // 提交成功后，刷新步骤2
      initTasks();
    } catch (error) {
      throw error;
    }
  };

  // 切换tab清空数据
  onBeforeUpdate(() => {
    commissionRefs.value = [];
    subcontractRefs.value = [];
  });

  defineExpose({
    canReturn,
    initTasks,
  });

  // 给form组件传值
  provide('saveAll', saveAll);
  provide('canReturn', canReturn);
  provide('message', useMessage());
  provide('initTasks', initTasks);
  provide('openContractPush', openContractPush);
</script>

<style scoped>
/* 左边tab样式 */
:deep(.ant-tabs-tab-btn){
  display: flex; /* tab的图标和文字居中 */
}

.tab-name{
  display: inline-block;
  text-align: left;
  width: 150px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 内容高度设置 */
:deep(.ant-tabs-content){
  height: 100%;
}

/* 表单距离左边tab距离 */
:deep(.ant-tabs-tabpane){
  padding-left: 0px !important;
}

/* 推送组件样式 */
.push-eare{
  z-index: 999;
}
</style>
